package com.bgds.sys.common.excel;//package com.duyi.hongqi.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 导出Excel工具类
 *
 * @author lj
 * version 1.0
 */
@Slf4j
public class EasyExcelExcelUtil<T> {


    /**
     *
     * @param response
     * @param titleName 导出文件的名称
     * @param list  导出数据集合
     * @param genericClass 导出数据对应的泛型类
     * @throws IOException
     */
    public static void downLoadExecl( HttpServletResponse response, String titleName, List<?> list, Class<?> genericClass) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(titleName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), genericClass)
                .sheet("sheet0")
                // 设置字段宽度为自动调整，不太精确
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(list);
    }

    /**
     *
     * @param file 解析的文件
     * @param pojoClass 接续数据对应的泛型类
     * @param sheetIndex 解析的sheet下标
     * @param headRowIndex 标题所在行数的下标
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> List<T> importExcel(MultipartFile file, Class<?> pojoClass,Integer sheetIndex,Integer headRowIndex)throws Exception {
        InputStream inputStream = file.getInputStream();
        List<T> list= EasyExcel.read(inputStream)
                .head(pojoClass)
                // 设置sheet,默认读取第一个
                .sheet()
                // 设置标题所在行数
                .headRowNumber(headRowIndex)
                .doReadSync();
        //关闭流
        inputStream.close();
        log.debug(list.toString());
        return list;
    }

}
